// ==UserScript==
// @name         Shujiajia Info Input
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  在shujiajia.com页面加载完成后弹出对话框，可输入信息并获取指定xpath标签的值。
// @author       wushifengcn@qq.com
// @match        https://www.shujiajia.com/*
// @match        https://shujiajia.com/*
// @grant        none
// ==/UserScript==

(function () {
  "use strict";

  function createLabel(dialog, text) {
    var label = document.createElement("label");
    label.style.fontWeight = "bold";
    label.textContent = text;
    dialog.appendChild(label);
    return label;
  }
  function createLabelInput(dialog, text) {
    var label = document.createElement("label");
    label.style.fontWeight = "bold";
    label.textContent = text;
    dialog.appendChild(label);

    let input = document.createElement("input");
    input.style.width = "80px";
    //input = document.createElement("textarea");
    //input.rows = 3;
    input.type = "text";
    dialog.appendChild(input);
    return input;
  }
  function createBtn(dialog, text) {
    let btn = document.createElement("button");
    btn.style.border = "2px solid #007BFF"; // Add a blue border
    btn.style.borderRadius = "2px"; // Round the corners
    btn.textContent = text;
    dialog.appendChild(btn);
    return btn;
  }
  function createSplit(dialog) {
    const hr = document.createElement("hr");
    hr.style.border = "1px solid #ccc";
    hr.style.margin = "1px 0";
    dialog.appendChild(hr);
  }
  function copyFromClipboard(input) {
    navigator.permissions.query({ name: "clipboard-read" }).then((result) => {
      if (result.state === "granted" || result.state === "prompt") {
        navigator.clipboard
          .readText()
          .then((text) => {
            input.value = text;

            if (input.id === "idQSN") {
              console.log("set new iD", text);
              localStorage.setItem("questionNumber", text);
            }
            navigator.clipboard.writeText("");
          })
          .catch((err) => {
            console.error("Failed to read clipboard contents: ", err);
          });
      } else {
        console.error("Clipboard read permission is not granted");
      }
    });
  }
  function getWorkFrameDoc() {
    let bdIframe = document.getElementById("bdIframe");
    if (bdIframe) {
      return bdIframe.contentWindow.document;
    }
    alert("找不到iframe");
    return null;
  }
  const inputEvent = new Event("input", { bubbles: true });
  const changeEvent = new Event("change", { bubbles: true });
  function triggerInputEvent(elem) {
    elem.dispatchEvent(inputEvent);
    elem.dispatchEvent(changeEvent);
  }

  //DOMContentLoaded事件 它在 DOM 树构建完成后就触发，不等待图片等资源加载完成。
  //load事件 是在页面的所有资源（包括图片、脚本等）都加载完成后触发，而不仅仅是 DOM 元素就绪
  //window.addEventListener("load",

  const dlgID = "hack_dialogShujiajia";
  function createDialog() {
    console.log("shujiajia...");
    var dialog = document.createElement("div");
    dialog.id = dlgID;
    dialog.style.position = "fixed";
    dialog.style.top = "auto";
    dialog.style.left = "10px";
    dialog.style.bottom = "30px";
    dialog.style.right = "auto";
    dialog.style.transform = "none";
    dialog.style.zIndex = "9999";
    dialog.style.backgroundColor = "white";
    dialog.style.padding = "20px";
    dialog.style.border = "1px solid black";

    //整题的处理
    createLabel(dialog, "题id");

    var inputQuestionNumber = document.createElement("input");
    inputQuestionNumber.style.width = "100px";
    inputQuestionNumber.id = "idQSN";
    inputQuestionNumber.type = "number";
    // Get the value from localStorage
    const storedQuestionNumber = localStorage.getItem("questionNumber");
    if (storedQuestionNumber) {
      inputQuestionNumber.value = storedQuestionNumber;
    } else {
      inputQuestionNumber.value = 200;
    }
    // Listen for changes to the input value and save it to localStorage
    inputQuestionNumber.addEventListener("change", function () {
      console.log("change");
      localStorage.setItem("questionNumber", inputQuestionNumber.value);
    });
    dialog.appendChild(inputQuestionNumber);

    let btnCopyId = createBtn(dialog, "拷id");
    btnCopyId.addEventListener("click", () => {
      copyFromClipboard(inputQuestionNumber);
    });

    //一个可以选择的下拉框，可选项有 选择题 填空题 解答题
    var selectQuestion = document.createElement("select");
    ["选择题", "填空题", "解答题", "判断题"].forEach(function (optionText) {
      var option = document.createElement("option");
      option.value = optionText;
      option.textContent = optionText;
      selectQuestion.appendChild(option);
    });
    dialog.appendChild(selectQuestion);

    let btnWhole = createBtn(dialog, "1 插整题");
    btnWhole.addEventListener("click", () => {
      console.log("题id", inputQuestionNumber.value, selectQuestion.value);

      let innerDoc = getWorkFrameDoc();
      let formId = innerDoc.querySelector("div[formid] > :first-child");
      let ims = formId.querySelectorAll("input.el-input__inner");
      //ims[0].value = "题目整图";
      //题型
      ims[3].value = selectQuestion.value;
      triggerInputEvent(ims[3]);
      //问题id
      let idQue = formId.querySelector("textarea.el-textarea__inner");
      idQue.value = inputQuestionNumber.value;
      triggerInputEvent(idQue);
    });
    createSplit(dialog);
    console.log("1 整题的处理done");

    ///
    let question = createLabelInput(dialog, "问题");
    let btnCopyQ = createBtn(dialog, "拷");
    btnCopyQ.style.color = "red";
    btnCopyQ.addEventListener("click", () => {
      copyFromClipboard(question);
    });
    //答案可以拷贝：对于数学公式使用
    let answer = createLabelInput(dialog, "答案");
    let btnCopyA = createBtn(dialog, "拷");
    btnCopyA.style.color = "blue";
    btnCopyA.addEventListener("click", () => {
      copyFromClipboard(answer);
    });
    //答案也可以直接选择
    var selectAnswer = document.createElement("select");
    selectAnswer.addEventListener("change", function () {
      answer.value = this.value;
    });
    ["A", "B", "C", "D", "E"].forEach(function (optionText) {
      var optionAnswer = document.createElement("option");
      optionAnswer.value = optionText;
      optionAnswer.textContent = optionText;
      selectAnswer.appendChild(optionAnswer);
    });
    dialog.appendChild(selectAnswer);
    //
    let analysis = createLabelInput(dialog, "解析");
    let btnCopyS = createBtn(dialog, "拷");
    btnCopyS.style.color = "green";
    btnCopyS.addEventListener("click", () => {
      copyFromClipboard(analysis);
    });
    let btnInsert2 = createBtn(dialog, "2 插问题");
    btnInsert2.addEventListener("click", () => {
      if (
        question.value === "" ||
        //answer.value === "" ||
        analysis.value === ""
      ) {
        alert("问题或解析为空");
        return;
      }

      let innerDoc = getWorkFrameDoc();
      let ans = innerDoc.querySelectorAll("div.markdown-wrap");
      //题干文本 - 输入区域
      let qMain = ans[0].querySelector("textarea");
      qMain.value = question.value;
      triggerInputEvent(qMain);
      console.log("题干文本", qMain.value);
      //答案 - 输入区域
      let qAns = ans[1].querySelector("textarea");
      qAns.value = answer.value; //"答案";
      triggerInputEvent(qAns);
      console.log("答案", qAns.value);
      //解析 - 输入区域
      let qExp = ans[2].querySelector("textarea");
      qExp.value = analysis.value; //"解析";
      triggerInputEvent(qExp);
      console.log("解析", qExp.value);
      //alert("插入成功");

      question.value = "";
      //answer.value = "";
      analysis.value = "";
    });
    console.log("2 问题和解析的处理done");

    //
    createSplit(dialog);
    let answerList = createLabelInput(dialog, "选项");
    let btnAnswer = createBtn(dialog, "拷");
    btnAnswer.addEventListener("click", () => {
      copyFromClipboard(answerList);
    });
    let btnAnswerListInsert = createBtn(dialog, "3 插选项框");
    btnAnswerListInsert.addEventListener("click", () => {
      if (answerList.value === "") {
        alert("选项内容为空");
        return;
      }
      let innerDoc = getWorkFrameDoc();
      //选项转写 - 输入区域
      let answerText = innerDoc
        .querySelectorAll("div.markdown-wrap")[0]
        .querySelector("textarea");
      answerText.value = answerList.value;
      triggerInputEvent(answerText);
    });

    createLabel(dialog, "__");
    let btnAnswerInsert = createBtn(dialog, "4 插答案框");
    btnAnswerInsert.addEventListener("click", () => {
      if (answer.value === "") {
        alert("答案框内容为空");
        return;
      }
      let innerDoc = getWorkFrameDoc();
      //选项转写 - 输入区域
      let answerText = innerDoc
        .querySelectorAll("div.markdown-wrap")[0]
        .querySelector("textarea");
      answerText.value = answer.value;
      triggerInputEvent(answerText);
    });

    // //debug reload
    // let btnReload = createBtn(dialog, "reload");
    // btnReload.addEventListener("click", () => {
    //   console.log("reload::", dlgID);
    //   let did = document.getElementById(dlgID);
    //   if (did) {
    //     did.remove();
    //     createDialog();
    //   }
    // });

    //
    document.body.appendChild(dialog);
  }
  //);

  //有的机器上load和DOMContentLoaded事件都不触发
  //页面包含了 iframe，对根页面进行处理,防止弹出多个
  if (document.URL.startsWith("https://shujiajia.com/studio/")) {
    console.log("shujiajia dialog:", dlgID);
    if (document.getElementById(dlgID)) {
      console.log("shujiajia is exist");
    } else {
      createDialog();
    }
  } else {
    console.log("not shujiajia root");
  }
})();
